package main.java.环形数组实现队列;

import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;

public class ArrayQueue1<E> implements Queue<E>, Iterable<E> {

    private E[] array;
    private int head = 0;
    private int tail = 0;

    @SuppressWarnings("all")
    public ArrayQueue1(int capacity) {
        array = (E[]) new Object[capacity+1];
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 判断环形数组是否已满
     * @return
     */
    public boolean isFull() {
        return Integer.toUnsignedLong(tail + 1) % array.length == head;
    }

    @Override
    public boolean contains(Object o) {
        return false;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int cursor = head;
            @Override
            public boolean hasNext() {
                return cursor !=  tail;
            }

            @Override
            public E next() {
                E e = array[cursor];
                head = (int) (Integer.toUnsignedLong((head + 1)) % array.length);
                return e;
            }
        };
    }

    @Override
    public Object[] toArray() {
        return new Object[0];
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return null;
    }

    @Override
    public boolean add(E e) {
        return false;
    }

    @Override
    public boolean remove(Object o) {
        return false;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        return false;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return false;
    }

    @Override
    public void clear() {

    }

    @Override
    public boolean offer(E e) {
        if (isFull()) {
            return false;
        }
        array[tail] = e;
        tail = (int) (Integer.toUnsignedLong((tail + 1)) % array.length);
        return true;
    }

    @Override
    public E remove() {
        if (isEmpty()) {
            return null;
        }
        E e = array[head];
        head = (int) (Integer.toUnsignedLong((head + 1)) % array.length);
        return e;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    @Override
    public E element() {
        return null;
    }

    @Override
    public E peek() {
        return null;
    }
}
